<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }
        .box {
            position: absolute;
            top: 0;
            left: 0;
            width: 100px;
            height: 100px;
            background-color: pink;
        }
        button{
            margin-top: 200px;
        }
    </style>
</head>

<body>
    <div class="box"></div>
    <button class="btn1" onclick="goNext(400)">400</button>
    <button class="btn2" onclick="goNext(800)">800</button>
    <script>
        var box = document.querySelector('.box');
        var btn1 = document.querySelector('.btn1');
        var btn2 = document.querySelector('btn2');

        function goNext(target) {
            move(box, target)
        }

        function move(el, target) {
            // 执行定时器之前， 清除老的定时器
            clearInterval(el.timer);
            // 满足current target相等 直接停止
            if (current === target) return;

            el.timer = setInterval(function () {
                // 获取当前位置 offsetLeft只取整数
                var current = el.offsetLeft;
                // 设置步长
                var step = (target - current) / 10;
                if (Math.abs(step) < 1) {
                    step = step > 0 ? 1 : -1;
                }
                // 移动起来
                current += step;
                el.style.left = current + 'px';
                // 设置停止
                if (current === target) {
                    clearInterval(el.timer)
                }
                
            }, 17)


        }

    </script>
</body>

</html>